name: Docker

on:
  release:
    types: [published]
  pull_request:
  push:
    tags:
      - "**"
    branches:
      - main
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: "${{ github.actor }}/johnbakhmat-tech"

jobs:
  docker:
    name: Build Image
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Cache docker layers
        uses: actions/cache@v3
        id: cache
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-

      - name: Gather Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
          labels: |
            cache-from=type=local,src=/tmp/.buildx-cache
            cache-to=type=local,dest=/tmp/.buildx-cache

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Get current tag
        id: get_tag
        run: echo ::set-output name=tag::$(echo $GITHUB_REF | sed -e 's,.*/\(.*\),\1,')

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          # push only on non-pr events
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache-new

      - name: Move cache
        run: |
          rm -rf /tmp/.buildx-cache
          mv /tmp/.buildx-cache-new /tmp/.buildx-cache
